//app.js
App({
  //设置全局请求URL
  globalData:{
    URL: 'https://www.ecollege.top',
    //URL: 'http://192.168.1.30',
  },
  wxRequest(method, url, data, callback, errFun) {
    swan.request({
      url: url,
      method: method,
      data: data,
      // 设置请求头
      header: {
        'content-type': method == 'GET'?'application/json':'application/x-www-form-urlencoded',
        'Accept': 'application/json'
      },
      dataType: 'json',
      success: function (res) {
        callback(res.data);
      },
      fail: function (err) {
        errFun(res);
      }
    })
  },

  onLaunch: function () {
    // 展示本地存储能力
    // var logs = swan.getStorageSync('logs') || []
    // logs.unshift(Date.now())
    // swan.setStorageSync('logs', logs)
     //设置全局请求URL

    // 获取用户信息
    /*swan.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          swan.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })*/
  },

  cache:{

    put(k, v, t) {
        var seconds = parseInt(t);
        if (seconds > 0) {
            var timestamp = Date.parse(new Date());
            var endTime = timestamp / 1000 + seconds;
            var entity = {
                endTime:endTime,
                value:v
            }
            swan.setStorageSync(k, entity)
        }
    },

    get(k) {
        var deadtime = swan.getStorageSync(k).endTime
        if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
            swan.removeStorageSync(k);
            return null;
        }else{
            return swan.getStorageSync(k).value
        }
    },

    remove(k) {
        swan.removeStorageSync(k);
    },

    clear() {
        swan.clearStorageSync();
    }
},

checkLoginStatus:{
    checkSession() {
        swan.checkSession({
            success: res => {
                console.log("登录状态有效",res)
            },
            fail: err => {
                console.log(err);
                app.showToastFail("登录状态过期！")
            }
        });
    }
},

showToastFail(content) {
    swan.showToast({
        title: content,
        mask: false,
        icon:'none'
    });
},
showToastSuccess(content) {
    swan.showToast({
        title: content,
        mask: false,
    });
},
showConfirmWarning(title,content) {
    swan.showModal({
        title: title,
        content: content,
        showCancel: true,
        confirmText: '确定',
        cancelText: '取消',
        cancelColor: '#000000',
        confirmColor: '#F7544F',
        success: res => {
            console.log('res',res.confirm)
        }
    });
},
/*'yyyy-MM-dd HH:mm:ss'格式的字符串转日期*/
stringToDate(str){
    let tempStrs = str.split(" ");
    let dateStrs = tempStrs[0].split("-");
    let year = parseInt(dateStrs[0], 10);
    let month = parseInt(dateStrs[1], 10) - 1;
    let day = parseInt(dateStrs[2], 10);
    let timeStrs = tempStrs[1].split(":");
    let hour = parseInt(timeStrs [0], 10);
    let minute = parseInt(timeStrs[1], 10);
    let second = parseInt(timeStrs[2], 10);
    let date = new Date(year, month, day, hour, minute, second);
    return date;
},

dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}
})